//
//  CircleInfoViewController.m
//  Lucky28
//
//  Created by zr on 2018/8/3.
//  Copyright © 2018年 zr. All rights reserved.
//

#import "CircleInfoViewController.h"
#import "CircleInfoTableViewCell.h"

@interface CircleInfoViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

@property (nonatomic, weak)UIImageView * iconImageView;
@property (nonatomic, weak)UILabel * nameLabel;
@property (nonatomic, weak)UILabel * timeLabel;
@property (nonatomic, weak)UILabel * titleLabel;
//@property (nonatomic, weak)UIImageView * contentImageView;
@property (nonatomic ,weak)UITextView * textView;
@property (nonatomic, weak)UILabel * bottomTimeLabel;
@property (nonatomic, weak)UIView * middleView;
@property (nonatomic, weak)UIView * bottomView;
@property (nonatomic, weak)UITableView * tableView;
@property (nonatomic, weak)UITextField * sayTextFiled;
@property (nonatomic, weak)UIButton * sayButton;
@property (nonatomic, weak)UIButton * likeButton;

@property (nonatomic, strong)NSArray * listArray;

@end

@implementation CircleInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupNav];
    [self setupUI];
}


- (void)setListArray:(NSArray *)listArray{
    
    _listArray = listArray;
    
    [self.tableView reloadData];
}

- (void)viewWillAppear:(BOOL)animated{
    
    [self reloadData];
}

- (void)reloadData{
    
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString * token = [userDefaults objectForKey:@"token"];
    
    NSDictionary * dict = @{@"note_id":self.ID,@"token":token};
    
    [[NetworkTool sharedTools] POST:@"/index/Note/detail" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary * data = responseObject[@"data"];
        
        NSDictionary * user = data[@"user"];
        
        NSURL * url = [NSURL URLWithString:user[@"headimg"]];
        
        [self.iconImageView sd_setImageWithURL:url placeholderImage:ImageNamed(@"头像7")];
        
        self.nameLabel.text = user[@"username"];
        
        // timeStampString 是服务器返回的13位时间戳
        NSString *timeStampString  = data[@"ctime"];
        
        // iOS 生成的时间戳是10位
        NSTimeInterval interval    =[timeStampString doubleValue];
        NSDate *date               = [NSDate dateWithTimeIntervalSince1970:interval];
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd"];
        NSString *dateString       = [formatter stringFromDate: date];
        //    NSLog(@"服务器返回的时间戳对应的时间是:%@",dateString);
        
        self.timeLabel.text = dateString;
        
        NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
        [formatter1 setDateFormat:@"yyyy-MM-dd HH:mm"];
        NSString *dateString1       = [formatter1 stringFromDate: date];
        
        self.titleLabel.text = data[@"title"];
        self.textView.text = data[@"content"];
        self.bottomTimeLabel.text = dateString1;
        self.listArray = data[@"comments"];
        
        int is_praise = [data[@"is_praise"] intValue];
        
        if (is_praise == 0) {
            
            self.likeButton.selected = NO;
        }else if (is_praise == 1){
            
            self.likeButton.selected = YES;
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}


- (void)setupNav{
    
    self.title = @"发帖子";
    
    UIButton * backButton = [[UIButton alloc] init];
    
    backButton.frame = CGRectMake(0, 0, 12 * SCREENH6, 20 * SCREENH6);
    [backButton setImage:[UIImage imageNamed:@"1返回"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToView) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.leftBarButtonItem = leftButton;
    
}

- (void)setupUI{
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIImageView * iconImageView = [UIImageView new];
    
    //  把图片设置成圆形
    iconImageView.layer.cornerRadius = 25;//裁成圆角
    iconImageView.layer.masksToBounds = YES;//隐藏裁剪掉的部分
    
//    iconImageView.image = ImageNamed(@"头像7");
    
    self.iconImageView = iconImageView;
    
    [self.view addSubview:self.iconImageView];
    
    
    UILabel * nameLabel = [UILabel new];
    
    nameLabel.text = @"用户姓名";
    nameLabel.textColor = [UIColor blackColor];
    nameLabel.font = [UIFont systemFontOfSize:15 * SCREENH6];
    
    self.nameLabel = nameLabel;
    
    [self.view addSubview:self.nameLabel];
    
    
    UILabel * timeLabel = [UILabel new];
    
//    timeLabel.text = @"15分钟前";
    timeLabel.textColor = ColorWithRGB(0xB5B5B5);
    timeLabel.font = [UIFont systemFontOfSize:12 * SCREENH6];
    
    self.timeLabel = timeLabel;
    
    [self.view addSubview:self.timeLabel];
    
    
    UILabel * titleLabel = [UILabel new];
    
//    titleLabel.text = @"那就这样吧！";
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.font = [UIFont systemFontOfSize:15 * SCREENH6];
    
    self.titleLabel = titleLabel;
    
    [self.view addSubview:self.titleLabel];
    
    
//    UIImageView * contentImageView = [UIImageView new];
//
//    contentImageView.backgroundColor = [UIColor grayColor];
//
//    self.contentImageView = contentImageView;
//
//    [self.view addSubview:self.contentImageView];
    UITextView *textView =[[UITextView alloc] init];
    textView.backgroundColor= [UIColor whiteColor];
//    textView.text = self.contentString;
    textView.textColor = [UIColor blackColor];
    textView.editable = NO;
    textView.font = [UIFont systemFontOfSize:14 * SCREENH6];
    
    self.textView = textView;
    
    [self.view addSubview:self.textView];
    
    
    UILabel * bottomTimeLabel = [UILabel new];
    
//    bottomTimeLabel.text = @"2018-05-06 18:55";
    bottomTimeLabel.textColor = ColorWithRGB(0xB5B5B5);
    bottomTimeLabel.font = [UIFont systemFontOfSize:12 * SCREENH6];
    
    self.bottomTimeLabel = bottomTimeLabel;
    
    [self.view addSubview:self.bottomTimeLabel];
    //ECECEC
    
    UIView * middleView = [UIView new];
    
    middleView.backgroundColor = ColorWithRGB(0xECECEC);
    
    self.middleView = middleView;
    
    [self.view addSubview:self.middleView];
    
    
    UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 378 * SCREENH6, SCREEN_WIDTH, 170 * SCREENH6) style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = [UIColor whiteColor];
//    tableView.rowHeight = 80 * SCREENH6;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//    tableView.estimatedRowHeight = 80 * SCREENH6;//推测高度，必须有，可以随便写多少
//
//    tableView.rowHeight =UITableViewAutomaticDimension;//iOS8之后默认就是这个值，可以省略
    
    self.tableView = tableView;
    
    [self.tableView registerClass:[CircleInfoTableViewCell class] forCellReuseIdentifier:@"circleInfoListCell"];
    
    [self.view addSubview:self.tableView];
    
    
    UIView * bottomView = [UIView new];
    
    bottomView.backgroundColor = ColorWithRGB(0xECECEC);
    bottomView.userInteractionEnabled = YES;
    
    self.bottomView = bottomView;
    
    [self.view addSubview:self.bottomView];
    
    
    UITextField * sayTextFiled = [[UITextField alloc] init];
    
    sayTextFiled.borderStyle = UITextBorderStyleNone;
    sayTextFiled.backgroundColor = [UIColor whiteColor];
    //设置光标颜色
    sayTextFiled.tintColor = [UIColor blackColor];
    //修改占位符文字颜色
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSForegroundColorAttributeName] = [UIColor grayColor];
    attrs[NSFontAttributeName] = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    sayTextFiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"写点什么" attributes:attrs];
    sayTextFiled.textColor = [UIColor blackColor];
    sayTextFiled.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 22 * SCREENH6, 0)];
    //设置显示模式为永远显示(默认不显示)
    sayTextFiled.leftViewMode = UITextFieldViewModeAlways;
    sayTextFiled.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    UIView * rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 35 * SCREENH6, 20 * SCREENH6)];
    UIImageView *image=[[UIImageView alloc] initWithFrame:CGRectMake(5, 0, 15 * SCREENH6, 20 * SCREENH6)];//WithImage:[UIImage imageNamed:@"手机号"]];
    image.image = ImageNamed(@"xie");
    [rightView addSubview:image];
    sayTextFiled.leftView = rightView;
    sayTextFiled.leftViewMode = UITextFieldViewModeAlways;
    sayTextFiled.returnKeyType = UIReturnKeyDone;
    sayTextFiled.delegate = self;
    
    self.sayTextFiled = sayTextFiled;
    
    [self.bottomView addSubview:self.sayTextFiled];
    
    
    UIButton * sayButton = [UIButton new];
    
    [sayButton setImage:ImageNamed(@"pinglun") forState:UIControlStateNormal];
    [sayButton addTarget:self action:@selector(clickBottomButton:) forControlEvents:UIControlEventTouchUpInside];
    
    self.sayButton = sayButton;
    
    [self.bottomView addSubview:self.sayButton];
    
    
    UIButton * likeButton = [UIButton new];
    
    [likeButton setImage:ImageNamed(@"dianzan") forState:UIControlStateNormal];
    [likeButton setImage:ImageNamed(@"dianzan2") forState:UIControlStateSelected];

    [likeButton addTarget:self action:@selector(clickBottomButton:) forControlEvents:UIControlEventTouchUpInside];
    
    self.likeButton = likeButton;
    
    [self.bottomView addSubview:self.likeButton];
}



- (void)viewDidLayoutSubviews{
    
    [self.iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.width.mas_equalTo(50 * SCREENH6);
        make.leading.mas_equalTo(self.view).offset(15 * SCREENH6);
        make.top.mas_equalTo(self.view).offset(15 * SCREENH6);
    }];
    
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.iconImageView.mas_trailing).offset(15 * SCREENH6);
        make.top.mas_equalTo(self.view).offset(20 * SCREENH6);
    }];
    
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.nameLabel);
        make.top.mas_equalTo(self.nameLabel.mas_bottom).offset(7 * SCREENH6);
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.iconImageView);
        make.top.mas_equalTo(self.iconImageView.mas_bottom).offset(10 * SCREENH6);
    }];
    
//    [self.contentImageView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.leading.mas_equalTo(self.iconImageView);
//        make.top.mas_equalTo(self.iconImageView.mas_bottom).offset(35 * SCREENH6);
//        make.width.mas_equalTo(180 * SCREENH6);
//        make.height.mas_equalTo(250 * SCREENH6);
//    }];
    
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.iconImageView);
        make.top.mas_equalTo(self.iconImageView.mas_bottom).offset(35 * SCREENH6);
        make.trailing.mas_equalTo(self.view).offset(-15 * SCREENH6);
        make.height.mas_equalTo(250 * SCREENH6);
    }];

    
    [self.bottomTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.textView);
        make.top.mas_equalTo(self.textView.mas_bottom).offset(7 * SCREENH6);
    }];
    
    [self.middleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.view);
        make.height.mas_equalTo(3 * SCREENH6);
        make.top.mas_equalTo(self.bottomTimeLabel.mas_bottom).offset(5 * SCREENH6);
    }];
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).offset(549 * SCREENH6);
        make.leading.trailing.bottom.mas_equalTo(self.view);
    }];
    
    [self.sayTextFiled mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.bottomView);
        make.leading.mas_equalTo(self.bottomView).offset(15 * SCREENH6);
        make.width.mas_equalTo(210 * SCREENH6);
        make.height.mas_equalTo(30 * SCREENH6);
    }];
    
    [self.likeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.bottomView).offset(-25 * SCREENH6);
        make.width.height.mas_equalTo(14.5 * SCREENH6);
        make.centerY.mas_equalTo(self.bottomView);
    }];
    
    [self.sayButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.likeButton.mas_leading).offset(-35 * SCREENH6);
        make.width.height.mas_equalTo(15 * SCREENH6);
        make.centerY.mas_equalTo(self.bottomView);
    }];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    return self.listArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CircleInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"circleInfoListCell" forIndexPath:indexPath];

//    cell.model = self.listArray[indexPath.row];
//    CircleInfoModel * model = self.listArray[indexPath.row];
//
//    NSURL * url = [NSURL URLWithString:model.user_headimg];
//
//    [cell.iconImageView sd_setImageWithURL:url placeholderImage:ImageNamed(@"头像7")];
//    cell.nameLabel.text = model.user_name;
//    cell.explationLabel.text = model.content;
//
//    // timeStampString 是服务器返回的13位时间戳
//    NSString *timeStampString  = model.ctime;
//
//    // iOS 生成的时间戳是10位
//    NSTimeInterval interval    =[timeStampString doubleValue];
//    NSDate *date               = [NSDate dateWithTimeIntervalSince1970:interval];
//
//    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//    [formatter setDateFormat:@"yyyy-MM-dd"];
//    NSString *dateString       = [formatter stringFromDate: date];
//    //    NSLog(@"服务器返回的时间戳对应的时间是:%@",dateString);
//
//    cell.timeLabel.text = dateString;
    
    NSDictionary * dict = self.listArray[indexPath.row];
    
    cell.nameLabel.text = dict[@"user_name"];
    cell.explationLabel.text = dict[@"content"];
    NSURL * url = [NSURL URLWithString:dict[@"user_headimg"]];
    
    [cell.iconImageView sd_setImageWithURL:url placeholderImage:ImageNamed(@"头像7")];

    NSString *timeStampString  = dict[@"ctime"];
    
    // iOS 生成的时间戳是10位
    NSTimeInterval interval    =[timeStampString doubleValue];
    NSDate *date               = [NSDate dateWithTimeIntervalSince1970:interval];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateString       = [formatter stringFromDate: date];
    //    NSLog(@"服务器返回的时间戳对应的时间是:%@",dateString);
    
    cell.timeLabel.text = dateString;


    
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80 * SCREENH6;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}


- (void)clickBottomButton:(UIButton *)button{
    
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    NSString * user_id = [userDefaults objectForKey:@"user_id"];
    NSString * token = [userDefaults objectForKey:@"token"];
    
    if (button == self.likeButton) {
        
        NSDictionary * dict = @{@"user_id":user_id,@"note_id":self.ID,@"type":@"1",@"token":token};
        
        [[NetworkTool sharedTools] POST:@"/index/Note/addCollect" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
//            NSLog(@"res===%@",responseObject);
            int status = [responseObject[@"status"] intValue];
            
            if (status == 200) {
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"ReLoadDataForTableview" object:nil];
            }else{
                
                NSString * string = [NSString stringWithFormat:@"%@",responseObject[@"msg"]];
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:string
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          //响应事件
                                                                          //                                                                          NSLog(@"action = %@", action);
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }
                
            }failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }else{
        
        [self.sayTextFiled becomeFirstResponder];
    }
}


//实现UITextField代理方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];//取消第一响应者
    
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    NSString * user_id = [userDefaults objectForKey:@"user_id"];
    NSString * token = [userDefaults objectForKey:@"token"];
    
    NSDictionary * dict = @{@"user_id":user_id,@"note_id":self.ID,@"content":self.sayTextFiled.text,@"token":token};
    
    [[NetworkTool sharedTools] POST:@"/index/Note/comment" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
//        NSLog(@"===%@",responseObject);
        
        int status = [responseObject[@"status"] intValue];
        
        if (status == 200) {
            
            self.sayTextFiled.text = @"";
            
            [self reloadData];
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:responseObject[@"msg"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      //响应事件
                                                                      //                                                                          NSLog(@"action = %@", action);
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
            
        }

        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
    return YES;
}


- (void)backToView{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
